package com.zhujiaji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhujiaji.common.Result;
import com.zhujiaji.mapper.PermissionMapper;
import com.zhujiaji.pojo.Permission;
import com.zhujiaji.service.PermissionService;
import com.zhujiaji.vo.Meta;
import com.zhujiaji.vo.RouterVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 朱佳吉
 * @date 2024/3/17 13:21
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Override
    public Result<List<RouterVo>> getRouter() {
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(Permission::getType, 2);
        List<Permission> permissions = baseMapper.selectList(wrapper);
        List<RouterVo> routerVoList = getPermissionTree(permissions, 0);
        return Result.ok(routerVoList);
    }

    public List<RouterVo> getPermissionTree(List<Permission> permissions, int parentId) {
        List<RouterVo> routerVoList = new ArrayList<>();
        for (Permission p:
             permissions) {
            if (p.getParentId() == parentId) {
                // 是要找的
                RouterVo r = new RouterVo();
                r.setName(p.getName());
                r.setPath(p.getPath());
                r.setComponent(p.getUrl());
                Meta meta = new Meta();
                meta.setTitle(r.getName());
                meta.setRoles(baseMapper.selectRolesById(p.getId()));
                meta.setIcon("icon");
                r.setMeta(meta);
                r.setChildren(getPermissionTree(permissions, p.getId()));
                routerVoList.add(r);
            }
        }
        return routerVoList;
    }
}
